import React, { useState, useEffect } from 'react';
import { Form, Button, message, Select, Card, Switch , Modal, Input, Table } from 'antd';
import { history, connect, ConnectProps, Dispatch } from 'umi';
import { ExclamationCircleOutlined, InfoCircleFilled, CloseOutlined, ArrowLeftOutlined, CopyOutlined, PlusOutlined } from '@ant-design/icons'
import { FORM_LAYOUT } from '@/utils/const';
import { getTypes, addEdgeNodeGroup, listAPI } from './service';
import trans from '@/utils/translate';
import { PageContainer } from '@ant-design/pro-layout';
import { edgeRequest } from '@/utils/request';
import ATable from '@apulis/table';
import { getStatus } from './status';
import type { NodeStateType } from './model';
import type { ATableColumn, SearchToolBarProps } from '@apulis/table';
interface node {
  name: string,
  describe?: string,
  nodeType: string,
};
interface TableItemType {
  status: string;
  nodeId: string;
  nodeName: string;
};

interface Props extends ConnectProps {
  dispatch: Dispatch;
  node: NodeStateType;
}
const { Option } = Select;
const Add: React.FC<Props> = (props) => {
  const [form] = Form.useForm();
  const [types, setTypes] = useState([]);
  const [hasDownload, setHasDownload] = useState(false);
  const [modal, setModal] = useState(false);
  const [nodesSelected, setNodesSelected] = useState<any[]>([]);
  // const [nodesSelected, setNodesSelected] = useState<React.Key[]>([]);
  const { dispatch } = props;
  const Item = Form.Item;
  const selectNode = () => {
    setModal(true);
  }
  const columns: ATableColumn<TableItemType>[] = [
    {
      title: trans('nodeManagement.edgeNode.nodeName'),
      dataIndex: 'nodeName',
    },
    {
      title: trans('nodeManagement.edgeNode.nodeType'),
      dataIndex: 'nodeType',
    },
    {
      title: trans('nodeManagement.edgeNode.status'),
      dataIndex: 'status',
      render: (text, record) => getStatus(text)
    },
    {
      title: trans('nodeManagement.edgeNode.createdAt'),
      dataIndex: 'createdAt',
      sortable: true,
      format: 'time',
      // render: (text) => format(text),
    },
  ];
  const columnsShow = [...columns, {
    title: trans('nodeManagement.edgeNode.operation'),
    render: (text: any, record: any, index: number) =>
      <a onClick={() => handleDelete(index)} style={{ marginRight: 8, color: 'red' }}>
        {trans('common.delete')}
      </a>
  }]

  const create = (e: node) => {
    const nodeIds = nodesSelected.map(n => n.nodeId);
    dispatch({ type: 'node/setTab', payload: { tab: 'group' }})
    addEdgeNodeGroup({ ...e, ...{ nodeIds }}).then(res => {
      if (res && res.code === 0) {
        message.success('创建成功');
        dispatch({ type: 'node/setTab', payload: { tab: 'group' }});
        history.push('/node-management/edge-node');
      }
    })
    console.log(e);
  }
  const handleDelete = (index: number) => {
    const nodesTemp = [...nodesSelected];
    nodesTemp.splice(index, 1);
    setNodesSelected(nodesTemp);
  }

  useEffect(() => {
    getTypes().then(res => {
      if (res && res.code === 0) {
        setTypes(res.data.nodeTypes);
      } else {
        message.error('未获取到类型');
      }
    })
  }, [])

  return (
    <PageContainer
      onBack={() => {
        hasDownload ? history.push('/node-management/edge-node') :
        Modal.confirm({
          centered: true,
          closable: true,
          icon: <ExclamationCircleOutlined />,
          maskClosable: true,
          okType: 'danger',
          okText: '确认',
          cancelText: '取消',
          width: '30%',
          title: <div style={{ fontWeight: 'bold' }}>确定退出么？</div>,
          content: <div>当前页面的数据不会保存</div>,
          onOk: async () => {
            history.push('/node-management/edge-node');
            dispatch({ type: 'node/setTab', payload: { tab: 'group' }});
          },
          cancelButtonProps: {},
          onCancel: () => {},
        });
      }}
    >
      <Card>
        <Form
          form={form}
          onFinish={(values) => create(values)}
          {...FORM_LAYOUT}
        >
          <Item
            label={trans('nodeManagement.edgeNode.nodeGroupName')}
            name='name'
            rules={[
              { required: true, message: '请输入边缘节点组名称' },
              {
                pattern: new RegExp(/^[a-zA-Z\u4e00-\u9fa5]+/, 'g'),
                message: '只能中英文开头',
              },
              {
                pattern: new RegExp(/^[a-zA-Z0-9\u4e00-\u9fa5\-_.]+$/, 'g'),
                message: '不可包含特殊字符',
              },
              { pattern: new RegExp(/^\S*\S+\S*$/, 'g'), message: '不能包含空格等空白符' },
              {
                pattern: new RegExp(/^.{1,20}$/, 'g'),
                message: '不能超过20个字符',
              },
            ]}
          >
            <Input></Input>
          </Item>
          <Item
            label={trans('nodeManagement.edgeNode.describe')}
            name='describe'
          >
            <Input.TextArea autoSize={{minRows:3}} placeholder='请输入描述，限制 200 字符以内' maxLength={200} showCount />
          </Item>
          <Item
            label={trans('nodeManagement.edgeNode.nodeType')}
            rules={[{ required: true, message: '请选择节点类型' }]}
            name='nodeType'
          >
            <Select>
              {
                types?.map(item => <Option value={item} key={item}>{item}</Option>)
              }
            </Select>
          </Item>
          <Item
            label={ trans('nodeManagement.edgeNode.selectNode')}
            required
          >
            <Button onClick={selectNode} icon={<PlusOutlined />}>{ trans('nodeManagement.edgeNode.selectEdgeNode')}</Button>
            <Modal
              visible={modal}
              width='800px'
              title={trans('nodeManagement.edgeNode.selectNode')}
              onCancel={()=>{
                setNodesSelected([]);
                setModal(false);
              }}
              onOk={()=>setModal(false)}
            >
              <ATable
                columns={columns}
                request={edgeRequest}
                dataSourceAPIPath={listAPI}
                reloadIcon={false}
                rowSelection={{
                  type:'checkbox',
                  selectedRowKeys: nodesSelected.map(n => n.nodeId),
                  // selectedRows: nodesSelected,
                  onChange: (selectedRowKeys, selectedRows) => {
                    setNodesSelected(selectedRows);
                  },
                }}
                rowKey='nodeId'
              ></ATable>
            </Modal>
            {
              nodesSelected.length > 0 &&
              <Table
                columns={columnsShow}
                dataSource={nodesSelected}
                rowKey='nodeId'
              ></Table>
            }

          </Item>
          <Item>
            <Button type='primary' htmlType='submit'>{trans('common.create')}</Button>
          </Item>
        </Form>
      </Card>
    </PageContainer>
  )
}

export default connect(({ node }: { node: NodeStateType }) => ({
  node,
}))(Add);
